package com.arrogames.blondbattle.game.graphics 
{
	import com.arrogames.blondbattle.game.combat.Health;
	import starling.display.MovieClip;
	import starling.display.Image;
	import starling.textures.Texture;
	import starling.textures.TextureAtlas;
	import starling.display.Sprite;
	import starling.core.Starling;
	
	import com.arrogames.blondbattle.game.graphics.animation.Animatable;
	import com.arrogames.blondbattle.game.movement.Spawner;
	import com.arrogames.blondbattle.game.combat.Faction;
	
	import com.arrogames.blondbattle.assets.AssetManager;
	
	/**
	 * ...
	 * @author ...
	 */
	public class UnitView extends Sprite implements Animatable
	{
		private var unitMovie:MovieClip;
		private var flag:Sprite;
		private var originalSpawn:String = "";
		private var textureName:String = "";
		
		public function UnitView(pName:String, pFactionName:String, health:Health)
		{
			textureName = pName.toLowerCase();
			originalSpawn = pFactionName;
			
			setAnimation();
			
			var flagView:SpawnFlag = new SpawnFlag(pFactionName);
			addChild(flagView);
			
			var healthBar:HealthBar = new HealthBar(unitMovie.width, 5, health);
			addChild(healthBar);
			healthBar.y = -healthBar.height;
			
			pivotX = unitMovie.width / 2;
			pivotY = unitMovie.height; 
			
			if (pFactionName == Faction.COMPUTER) {
				flagView.x = unitMovie.width;
			}
			flagView.y = unitMovie.height/2;
		}
		
		public function getOriginalSpawn() : String
		{
			return originalSpawn;
		}
		
		/**
		 * @param	pDirection
		 */
		public function changeDirection(pOriginalSpawn:String) : void
		{
			originalSpawn = pOriginalSpawn;
			
			//remove current animation
			Starling.juggler.remove(unitMovie);
			removeChild(unitMovie);
			
			setAnimation();
			
		}
		
		private function setAnimation() : void 
		{
			var frames:Vector.<Texture> = null;
			switch (originalSpawn) {
				case Faction.HUMAN:
					frames = AssetManager.instance.getTextures(textureName + "_east_");
					break;
				case Faction.COMPUTER:
					frames = AssetManager.instance.getTextures(textureName + "_west_");
					break;
			}
			//add new animation with correct direction
			unitMovie = new MovieClip(frames, 4);
			unitMovie.loop = true;
			addChild(unitMovie);
			Starling.juggler.add(unitMovie);
		}
		
		public function stopAnimation() : void
		{
			unitMovie.loop = false;
			unitMovie.stop();
		}
		
		public function startAnimation() : void 
		{
			unitMovie.loop = true;
			unitMovie.play();
		}
		
		public function isAnimating() : Boolean
		{
			return unitMovie.loop;
		}
		
	}

}